package com.jack.lib.base

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jack.lib.core.net.JBaseData
import com.scwang.smart.refresh.layout.SmartRefreshLayout

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/8/31
 * desc   :
 */
abstract class KtRefreshFragment<VB: ViewBinding> : BaseFragment<VB>() {

    companion object {
        const val DEFAULT_PAGE = 1
        const val DEFAULT_PAGE_SIZE = 10
    }
    protected open var page = DEFAULT_PAGE

    protected open var pageSize = DEFAULT_PAGE_SIZE

    protected lateinit var smartRefreshLayout: SmartRefreshLayout

    private val defaultRefreshLayout by lazy { SmartRefreshLayout(requireContext()) }

    protected open fun defaultRefreshLayout(inflater: LayoutInflater): SmartRefreshLayout = defaultRefreshLayout

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val childView = super.onCreateView(inflater, container, savedInstanceState)

        smartRefreshLayout = defaultRefreshLayout(inflater)
        smartRefreshLayout.setOnRefreshListener { refresh() }
        smartRefreshLayout.setOnLoadMoreListener { loadMore() }
        smartRefreshLayout.setBackgroundColor(Color.TRANSPARENT)

        if (smartRefreshLayout != defaultRefreshLayout) {
            return childView
        }
        smartRefreshLayout.addView(childView, ViewGroup.LayoutParams(-1,  -1))
        return smartRefreshLayout
    }

    fun refresh(){
        page = DEFAULT_PAGE
        onRefresh()
    }

    fun refresh(full: Boolean) {
        if (full) fullRefresh() else refresh()
    }

    fun fullRefresh() {
        pageSize *= page
        page = DEFAULT_PAGE
        onRefresh()
        pageSize = DEFAULT_PAGE_SIZE
    }

    fun loadMore(){
        page++
        onLoadMore()
    }

    fun enableRefresh(enabled: Boolean){
        smartRefreshLayout.setEnableRefresh(enabled)
    }

    fun enableLoadMore(enabled: Boolean){
        smartRefreshLayout.setEnableLoadMore(enabled)
    }

    fun finishRefreshAndLoadMore(adapter: BaseQuickAdapter<*, *>){
        smartRefreshLayout.finishRefresh()
        smartRefreshLayout.finishLoadMore()
        smartRefreshLayout.setNoMoreData(adapter.data.size < (pageSize * page).coerceAtLeast(pageSize))
    }

    override fun onFill(bean: JBaseData<*>) {
        super.onFill(bean)
        smartRefreshLayout.finishRefresh()
        smartRefreshLayout.finishLoadMore()
    }

    override fun onError(cause: Throwable) {
        super.onError(cause)
        smartRefreshLayout.finishRefresh()
        smartRefreshLayout.finishLoadMore()
    }

    abstract fun onRefresh()

    abstract fun onLoadMore()
}